// V-backend/src/controllers/productController.js
const { Product, ProductImage, Anchor } = require('../models');

// 获取所有商品
exports.getAllProducts = async (req, res) => {
  try {
    console.log('🛍️ 收到获取商品列表请求，查询参数:', req.query);
    
    const { page = 1, limit = 10, category, status, keyword } = req.query;
    const offset = (page - 1) * limit;
    
    // 构建查询条件
    const where = {};
    if (category) where.category = category;
    if (status) where.status = status;
    if (keyword) {
      const { Op } = require('sequelize');
      where[Op.or] = [
        { product_name: { [Op.like]: `%${keyword}%` } },
        { product_description: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    console.log('📝 商品查询条件:', where);
    
    // 先测试简单查询
    console.log('🔍 测试商品简单查询...');
    const testProducts = await Product.findAll({ 
      limit: 2,
      raw: true 
    });
    console.log('✅ 商品简单查询结果:', testProducts);
    
    const products = await Product.findAndCountAll({
      where,
      include: [
        {
          model: Anchor,
          as: 'anchor',
          attributes: ['anchor_id', 'anchor_name', 'avatar']
        }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });
    
    console.log('✅ 商品完整查询结果:', {
      查询到记录数: products.count,
      返回记录数: products.rows.length
    });
    
    // 格式化商品数据，适配前端
    const formattedProducts = products.rows.map(product => {
      const productData = product.get ? product.get({ plain: true }) : product;
      
      return {
        id: productData.product_id,
        product_id: productData.product_id,
        name: productData.product_name,
        description: productData.product_description,
        price: productData.price,
        stock: productData.stock_quantity,
        cover_image: productData.cover_image,
        category: productData.category,
        status: productData.status,
        anchor: productData.anchor || null,
        product_images: []
      };
    });
    
    res.json({
      success: true,
      data: formattedProducts,
      pagination: {
        current: parseInt(page),
        total: products.count,
        pages: Math.ceil(products.count / limit)
      }
    });
  } catch (error) {
    console.error('❌ 获取商品列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取商品列表失败',
      error: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
  }
};

// 获取单个商品详情
exports.getProductById = async (req, res) => {
  try {
    const { productId } = req.params;
    console.log('🛍️ 获取商品详情，ID:', productId);
    
    const product = await Product.findByPk(productId, {
      include: [
        {
          model: Anchor,
          as: 'anchor',
          attributes: ['anchor_id', 'anchor_name', 'avatar', 'anchor_info']
        }
      ]
    });
    
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    const productData = product.get ? product.get({ plain: true }) : product;
    
    // 格式化返回数据
    const formattedProduct = {
      id: productData.product_id,
      product_id: productData.product_id,
      name: productData.product_name,
      description: productData.product_description,
      price: productData.price,
      stock: productData.stock_quantity,
      cover_image: productData.cover_image,
      category: productData.category,
      status: productData.status,
      anchor: productData.anchor || null,
      product_images: []
    };
    
    res.json({
      success: true,
      data: formattedProduct
    });
  } catch (error) {
    console.error('获取商品详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取商品详情失败'
    });
  }
};

// 创建商品
exports.createProduct = async (req, res) => {
  try {
    const {
      anchor_id,
      product_name,
      product_description,
      price,
      original_price,
      stock_quantity,
      category,
      cover_image
    } = req.body;
    
    // 验证必要字段
    if (!anchor_id || !product_name || !price) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }
    
    const product = await Product.create({
      anchor_id,
      product_name,
      product_description,
      price,
      original_price: original_price || price,
      stock_quantity: stock_quantity || 0,
      category,
      cover_image,
      status: 'active'
    });
    
    res.status(201).json({
      success: true,
      message: '商品创建成功',
      data: product
    });
  } catch (error) {
    console.error('创建商品失败:', error);
    res.status(500).json({
      success: false,
      message: '创建商品失败'
    });
  }
};

// 更新商品
exports.updateProduct = async (req, res) => {
  try {
    const { productId } = req.params;
    const updateData = req.body;
    
    const product = await Product.findByPk(productId);
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    await product.update(updateData);
    
    res.json({
      success: true,
      message: '商品更新成功',
      data: product
    });
  } catch (error) {
    console.error('更新商品失败:', error);
    res.status(500).json({
      success: false,
      message: '更新商品失败'
    });
  }
};

// 删除商品
exports.deleteProduct = async (req, res) => {
  try {
    const { productId } = req.params;
    
    const product = await Product.findByPk(productId);
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    await product.destroy();
    
    res.json({
      success: true,
      message: '商品删除成功'
    });
  } catch (error) {
    console.error('删除商品失败:', error);
    res.status(500).json({
      success: false,
      message: '删除商品失败'
    });
  }
};

// 更新商品状态
exports.updateProductStatus = async (req, res) => {
  try {
    const { productId } = req.params;
    const { status } = req.body;
    
    const validStatuses = ['active', 'inactive', 'sold_out'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的状态值'
      });
    }
    
    const product = await Product.findByPk(productId);
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    await product.update({ status });
    
    res.json({
      success: true,
      message: '商品状态更新成功',
      data: product
    });
  } catch (error) {
    console.error('更新商品状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新商品状态失败'
    });
  }
};

// 获取主播的商品列表
exports.getProductsByAnchor = async (req, res) => {
  try {
    const { anchorId } = req.params;
    const { page = 1, limit = 10, status } = req.query;
    const offset = (page - 1) * limit;
    
    const where = { anchor_id: anchorId };
    if (status) where.status = status;
    
    const products = await Product.findAndCountAll({
      where,
      include: [
        {
          model: ProductImage,
          as: 'images',
          attributes: ['image_id', 'image_url', 'sort_order']
        }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });
    
    res.json({
      success: true,
      data: products.rows,
      pagination: {
        current: parseInt(page),
        total: products.count,
        pages: Math.ceil(products.count / limit)
      }
    });
  } catch (error) {
    console.error('获取主播商品列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取主播商品列表失败'
    });
  }
};